<?php

namespace Jinxing\Admin\Http\Controllers;

use Illuminate\Support\Arr;
use Jinxing\Admin\Models\Config;
use Jinxing\Admin\Repositories\ConfigRepository;
use Jinxing\Admin\Http\Requests\Admin\Configs\UpdateRequest;

/**
 * Class ConfigsController 配置信息
 *
 * @package Jinxing\Admin\Http\Controllers
 */
class ConfigsController extends Controller
{
    /**
     * @var ConfigRepository
     */
    protected $repository;

    public function __construct(ConfigRepository $configRepository)
    {
        $this->repository = $configRepository;
    }

    /**
     * 基本设置
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $config = $this->repository->pluck([], 'config', 'name')->toArray();
        return view('admin::configs.index', compact('config'));
    }

    /**
     * 系统注册设置
     *
     * @param UpdateRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UpdateRequest $request)
    {
        $data = $request->all();
        Arr::forget($data, ['_token', 'name']);

        /* @var $system Config */
        $system = $this->repository->firstOrCreate(['name' => $request->input('name')], [
            'config' => $data,
        ]);
        if (!$system) {
            return $this->error(404, '修改数据存在问题');
        }

        // 执行修改数据
        $system->config = array_merge($system->config, $data);
        if (!$system->save()) {
            return $this->error(404, '修改数据失败');
        }

        // 返回成功
        return $this->success($system->config, '修改成功');
    }
}
